package org.clockworkmages.games.anno1186;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class GameBeansContext {

	private static Map<Class<?>, Object> singletonBeans = new HashMap<Class<?>, Object>();

	public static void register(Object bean) {
		singletonBeans.put(bean.getClass(), bean);
	}

	public static <T> T getBean(Class<T> clazz) {
		return (T) singletonBeans.get(clazz);
	}

	public static void processInjectAnnotations(Object bean) {
		for (Field field : bean.getClass().getDeclaredFields()) {
			if (field.isAnnotationPresent(Injected.class)) {
				Class<?> fieldClass = field.getType();
				Object beanToInject = singletonBeans.get(fieldClass);
				if (beanToInject == null) {
					throw new RuntimeException(
							"Could not find any registered bean of type "
									+ fieldClass.getCanonicalName());
				}
				field.setAccessible(true);
				try {
					field.set(bean, beanToInject);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void processInjectAnnotations() {
		for (Object bean : singletonBeans.values()) {
			processInjectAnnotations(bean);
		}

	}
}
